package com.api.apigateway.config;


import com.api.apigateway.risk.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@Data
public class RiskConfig {

    //=======风控规则引擎硬阈值
    @Value("${risk.rule.qps.threshold:3.0}")
    private double qpsThreshold;

    @Value("${risk.rule.qps.delta:3.0}")
    private double deltaThreshold;

    @Value("${risk.rule.ua.min-length:8}")
    private int uaMinLength;

    @Value("${risk.rule.size.body:0}")
    private int bodySize;

    @Value("${risk.rule.size.query:4096}")
    private int querySize;

    @Value("${risk.rule.entropy:0.3}")
    private double entropy;

    @Bean
    public SlidingWindowStats slidingWindowStats(){ return new SlidingWindowStats(); }
    // 每分钟清理一次
    @Scheduled(fixedRate = 60_000)
    public void decayStats() {
        slidingWindowStats().decay();
    }
    @Bean public FeatureExtractor featureExtractor(SlidingWindowStats w){ return new FeatureExtractor(w); }
    @Bean public RulesEngine rulesEngine(){ return new RulesEngine(); }
    // 配置成你的模型与特征顺序（ORDER 必须与训练脚本一致）
    @Bean
    public ModelScorer modelScorer() {
        String[] ORDER = new String[]{
                "method_get","method_post","header_cnt","ua_len","query_size","body_size","param_cnt","is_ak_present",
                "has_user","user_mod_10","path_hash_mod_100",
                "qps_user_path","delta_user_path","entropy_ip","ip_hash_mod_1000","ua_hash_mod_1000"
        };
        // 模型放 resources/models/iforest.onnx
        return new OnnxIsolationScorer("classpath:models/iforest.onnx", ORDER, "scores");
    }
    @Bean public RiskService riskService(FeatureExtractor f, RulesEngine r, ModelScorer m){ return new RiskService(f,r,m); }

}
